<!--
  模块：专项申报 - 新增
-->
<template>
  <div class="declare-add">
    <AppMainHeader>
      <el-row>
        <el-col :span="24" class="align-right">
          <el-button type="primary" @click="handleAddSave">保存</el-button>
          <el-button type="primary" @click="handleAddSubmit">发布</el-button>
        </el-col>
      </el-row>
    </AppMainHeader>
    <AppMainContent>
      <el-card>
        <CardFormTitle title="申报信息" />
        <CardFormContent>
          <!-- 表单内容 -->
          <el-form
            :inline="true"
            label-position="top"
            :model="declareForm"
            ref="declareForm"
            :rules="rules"
            label-width="auto"
          >
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="申报标题" prop="title">
                  <el-input
                    clearable
                    class="formTitle"
                    v-model="declareForm.title"
                    prop="title"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="申报开始时间" prop="startTime">
                  <el-date-picker
                    type="datetime"
                    prefix-icon="el-icon-date"
                    v-model="declareForm.startTime"
                    prop="startTime"
                    format="yyyy-MM-dd HH:mm"
                    value-format="yyyy-MM-dd HH:mm"
                  ></el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="申报截止时间" prop="endTime">
                  <el-date-picker
                    type="datetime"
                    prefix-icon="el-icon-date"
                    v-model="declareForm.endTime"
                    prop="endTime"
                    format="yyyy-MM-dd HH:mm"
                    value-format="yyyy-MM-dd HH:mm"
                  ></el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="发布人" prop="publishUserName">
                  <el-input
                    :disabled="true"
                    :value="declareForm.publishUserName"
                    prop="publishUserName"
                    class="elInput"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="发布时间" prop="publishTime">
                  <el-input
                    :disabled="true"
                    prefix-icon="el-icon-date"
                    :value="declareForm.publishTime"
                    prop="publishTime"
                    class="elInput"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 上传 -->
            <el-form :inline="true" label-position="top">
              <el-form-item label="上传文件">
                <el-upload
                  class="upload-demo"
                  action=""
                  multiple
                  :limit="3"
                  :before-upload="handleBeforeUpload"
                  :before-remove="handleBeforeRemove"
                  accept=".doc,.docx,.xlsx,.xls,.ppt,.pptx,.pdf"
                  :file-list="fileList"
                  :http-request="handleHttpRequest"
                >
                  <!-- :headers="HandleHeader" -->
                  <!-- :auto-upload="false" -->
                  <el-button type="primary">上传文件</el-button>
                </el-upload>
              </el-form-item>
            </el-form>
            <!-- 富文本框 -->
            <el-form :inline="true" label-position="top">
              <el-form-item label="文本内容">
                <VueQuillEditor
                  :content.sync="declareForm.content"
                  :business-type="4"
                />
              </el-form-item>
            </el-form>
          </el-form>
        </CardFormContent>
      </el-card>
    </AppMainContent>
    <!-- 版权 -->
    <Copyright />
  </div>
</template>

<script>
  // * 版权
  import Copyright from '@/components/copyright'

  // * 保存和发布
  import { addSaveDeclare, addSubmitDeclare } from '@/api/declare/index'

  // * 上传
  import { upload } from '@/api/common'
  // // * 鉴权方法
  // import { getToken } from '@/utils/auth'

  export default {
    name: 'DeclareAdd',
    components: { Copyright },
    data() {
      return {
        // 输入框
        input: '',
        // 表单
        declareForm: {
          // 标题
          title: '',
          // 开始时间
          startTime: '',
          // 结束时间
          endTime: '',
          // 富文本框
          content: '',
          //创建时间
          createTime: '',
          //创建人ID
          createUserID: '',
          // 创建人姓名
          createUserName: '',
          // 发布人ID
          publishUserID: '',
          // 发布人姓名
          publishUserName: '',
          //发布时间
          publishTime: '',
          // 状态
          status: '',
        },
        rules:{
          title:[
            {required:true,message:'请输入申报标题',trigger:'blur'},
            {min:2,max:100,message:'标题长度必须为2-30位',trigger:'blur'}
          ],
          startTime:[
            {required:true,message:'请输入申报开始时间',trigger:'blur'},
          ],
          endTime:[
            {required:true,message:'请输入申报结束时间',trigger:'blur'},
          ]
        },
        // 上传文件
        fileList: [],
        // 是否删除
        delflag: '',
        // 上传请求头
        // HandleHeader: { Authorization: 'Bearer ' + getToken() },
      }
    },
    methods: {
      // 发布时间实时更新
      currentTime() {
        setInterval(this.formatDate, 500)
      },

      // 时间格式化
      formatDate() {
        let date = new Date()
        let year = date.getFullYear() // 年
        let month = date.getMonth() + 1 // 月
        let day = date.getDate() // 日
        this.declareForm.createTime = `${year}-${month}-${day}`
        this.declareForm.publishTime = `${year}-${month}-${day}`
      },

      // * 保存按钮操作
      handleAddSave() {
        let _this = this
        // 创建人
        _this.declareForm.createUserName = this.$store.state.user.userInfo.userName
        _this.declareForm.status = '1'
        _this.declareForm.publishTime = ''
        _this.declareForm.publishUserName=''
        new Date(this.declareForm.startTime) < new Date()
          ? this.$message.error('申报开始时间不得早于当前时间')
          : new Date(this.declareForm.startTime) >
            new Date(this.declareForm.endTime)
          ? this.$message.error('申报开始时间不得小于申报截止时间')
          : this.$refs['declareForm'].validate((valid) => {
              if (valid) {
                if (this.declareForm != undefined) {
                  addSaveDeclare(this.declareForm).then((response) => {
                    _this.$alert(
                      _this.declareForm.title + '添加成功！',
                      '消息',
                      {
                        confirmButtonText: '确定',
                        callback: (action) => {
                          window.location.reload()
                          window.location.href = '/declare/index'
                        },
                      }
                    )
                  })
                }
              }
            })
      },

      // * 提交按钮操作
      handleAddSubmit() {
        let _this = this
        _this.declareForm.status = '2'
        // 发布人ID
        _this.declareForm.publishUserID = this.$store.state.user.userInfo.id
        // 发布人
        _this.declareForm.publishUserName = this.$store.state.user.userInfo.userName
        // 创建人
        _this.declareForm.createUserName = this.$store.state.user.userInfo.userName
        new Date(this.declareForm.startTime) < new Date()
          ? this.$message.error('申报开始时间不得早于当前时间')
          : new Date(this.declareForm.startTime) >
            new Date(this.declareForm.endTime)
          ? this.$message.error('申报开始时间不得小于申报截止时间')
          : this.$refs['declareForm'].validate((valid) => {
              if (valid) {
                if (this.declareForm != undefined) {
                  addSubmitDeclare(this.declareForm).then((response) => {
                    _this.$alert(
                      _this.declareForm.title + '发布成功！',
                      '消息',
                      {
                        confirmButtonText: '确定',
                        callback: (action) => {
                          window.location.reload()
                          window.location.href = '/declare/index'
                        },
                      }
                    )
                  })
                }
              }
            })
      },
      // * 上传文件
      // 文件上传之前
      handleBeforeUpload(file) {
        let fileSize = file.size < 50 * 1024 * 1024
        let fileCount = fileSize + fileSize + fileSize < 100 * 1024 * 1024
        if (!fileSize) {
          this.$message({
            message: '上传文件单个文件大小不能超过 50MB！',
            type: 'warning',
          })
          return false
        }
        if (!fileCount) {
          this.$message({
            message: '总文件大小不能超过100MB！',
            type: 'warning',
          })
          return false
        }
      },
      // 上传
      handleHttpRequest(e) {
        let _this = this
        const loading = this.$loading({
          lock: true,
          text: 'Loading...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        // 把文件放入 FormData 进行提交
        let formData = new FormData()
        // console.log(formData)

        formData.append('file', e.file)
        // formData.append('businessType', this.businessType)

        upload(formData)
          .then((response) => {
            let data = formData.data
            let id = formData.id
            let filePath = formData.filePath
            let fileName = formData.fileName

            list = {
              id: id,
              uid: e.file.uid,
              filePath: filePath,
              fileName: fileName,
            }
            _this.fileList.push(list).loading.close()
          })
          .catch(() => {
            loading.close()
          })
      },
      // 移除
      handleBeforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`)
      },
    },
    created() {
      const _this = this
      // 创建人ID
      _this.declareForm.createUserID = this.$store.state.user.userInfo.id
      // 创建人姓名
      _this.declareForm.createUserName = this.$store.state.user.userInfo.userName
      // 发布人姓名
      _this.declareForm.publishUserName = this.$store.state.user.userInfo.userName
      // 发布日期
      _this.declareForm.publishTime = this.declareForm.createTime
    },
    mounted() {
      this.currentTime()
      this.formatDate()
    },
    //销毁定时器
    beforeDestroy() {
      if (this.formatDate) {
        clearInterval(this.formatDate) // 在Vue实例销毁前，清除时间定时器
      }
    },
  }
</script>

<style lang="scss" scoped>
  .declare-add {
    height: 100%;
    overflow: scroll;
  }

  @import '../declare-scss/index.scss';
</style>
